using UnityEngine;
using System.Collections;

public class RotateTowards : MonoBehaviour {
	
	/**
	 * http://forum.unity3d.com/threads/1211-Making-an-object-rotate-to-face-another
	 * Adapted to C# by André Nilsen
	 * */
	
	public Transform target;
	public Transform objectToRotate;
	public float strength = 0.5f;
	public bool freezeX = true;
	public bool freezeZ = true;
	
	public bool debug = false;
	
	private Quaternion targetRotation;
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	public void Update () {
		float str = Mathf.Min(strength * Time.deltaTime, 1);
		// Snippet from http://forum.unity3d.com/threads/36377-transform-LookAt-or-Quaternion-LookRotation-on-1-axis-only
		// Author: rocket5tim
		// Posted: 05:51 PM 12-18-2009
		targetRotation = Quaternion.LookRotation(target.position - objectToRotate.position);
		
		targetRotation.x = 0.0f;
    	targetRotation.z = 0.0f;
		
		objectToRotate.rotation = Quaternion.Slerp(objectToRotate.rotation, targetRotation, str);
		// Snippet END
		
		//objectToRotate.rotation = Quaternion.Lerp(objectToRotate.rotation, targetRotation, str);
	}
	
	public void OnGUI() {
		if (debug) {
			GUI.Box(new Rect(0,0,200,400), 
				"Object Rotation: " + objectToRotate.rotation + "\n" +
				"Object Angle Y:" + targetRotation.y + "\n" +
				"Diff: " + getDiff_Target());	
		}
	}
	
	public float getDiff_Target() {
		return Quaternion.Angle(objectToRotate.rotation, targetRotation);
	}
}
